Repository navigation
Install torch 2.13 on new Apple Silicon homes for the fused MPS attention kernel - #18428
Conversation
…tion kernel New macOS arm64 installs on macOS 14+ with a GIL-enabled Python 3.10 - 3.14 take torch 2.13 / torchvision 0.28 / torchaudio 2.11 from the cpu index, the first torch whose MPS SDPA runs a fused prefill kernel instead of materialising the score matrix. Existing homes keep a resident 2.4 - 2.14 release unless UNSLOTH_TORCH_UPGRADE=1, and the route needs the PyPI unsloth release to admit torch 2.13, as on cu130. torch 2.15 is not used: it has no cp310 macOS wheel and no matching torchvision. Also adds an MPS attention parity test at each image family's head shape against a CPU reference, recording whether the prefill kernel engaged.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codex Review Summary: ❌ FailedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
… macOS torch 2.13 new-install route [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…18659) ## Summary `unsloth studio update` re-resolves `unsloth` and `unsloth-zoo` with dependencies. On Linux and Windows x64, `_FreezeNewTorchForCoreUpdate` pins the resident torch, torchvision and torchaudio through `UV_OVERRIDE` while that happens, but only for torch >= 2.13. macOS had no freeze. Apple Silicon is moving to torch 2.13 for new installs only (#18428). Existing installs keep their torch unless the user runs a manual repair, which sets `UNSLOTH_TORCH_UPGRADE=1` through install.sh. Without a freeze, a released unsloth with a torch ceiling (2026.9.11 declared `torch<2.13.0`) could move a 2.13 Mac install back to 2.12 on `studio update`. A torch floor could also move a 2.11 install up. ## Change - `studio/install_python_stack.py`: on Apple Silicon (`darwin` + `arm64`), `_FreezeNewTorchForCoreUpdate` now freezes every resident plain `X.Y.Z` torch release, not only >= 2.13. install.sh already freezes the trio this way for every with-deps unsloth install, on every OS. The bundled `overrides-darwin-arm64.txt` is folded into the frozen file, minus any torch lines, so the MLX transformers / anyio / huggingface_hub overrides still apply. - Linux, Windows x64, Windows on ARM and Intel macOS behave exactly as before. The predicate for those hosts is unchanged, and an absent or non-release torch still returns early. - While the freeze is active, a uv failure on Apple Silicon now stops instead of falling back to pip. pip ignores `UV_OVERRIDE` and would honour the released cap. This is the same behaviour Linux already has under the freeze. ## Tests New file: `studio/backend/tests/test_macos_core_update_torch_freeze.py`, CPU only. - Apple Silicon at 2.11.0 / 2.12.1 / 2.13.0 / 2.14.0: the trio is pinned, the MLX overrides are folded in, and `UV_OVERRIDE` is restored afterwards. - An unset `UV_OVERRIDE` is restored to unset. - A uv failure under the freeze never runs pip. - These hosts are not frozen: Intel macOS, Apple Silicon without a release torch, Linux aarch64 at 2.12.1, Linux arm64 at 2.11.0, Windows arm64 at 2.12.1. Base (main) vs head: 6 tests fail on main and pass on the branch. The 6 host-unchanged cases pass on both. No head test fails. Across all 75 test files that import `install_python_stack` (8.5k tests), the head's failing test IDs are a subset of main's. The failures are pre-existing and come from this host's environment. They are identical apart from one ROCm spoof test that failed only on the main arm. ## Not covered - No real Apple Silicon run. The uv override semantics are the same ones the Linux freeze and install.sh rely on, but they were not exercised on a Mac here.
…amily on Apple Silicon (#18783) Below torch 2.13, every MPS `scaled_dot_product_attention` call runs on the MPSGraph path, which builds the full score matrix. Past about 0.9 * 2^29 score elements per call (macOS 15), that path returns wrong values: cosine 0.000 against an fp64 reference (pytorch#179352). #18428 moved new Apple Silicon installs to torch 2.13, whose prefill kernel never builds the scores. Existing homes keep their torch unless the user runs a repair with `UNSLOTH_TORCH_UPGRADE=1`, and only Qwen-Image-2.1 had a bound of its own. A single 1024 px FLUX call (24 heads x 4608 tokens, 2^28.92 elements) is right at that edge. Z-Image, FLUX.2 klein, SD3.5 and Qwen-Image go past it at the resolutions Studio offers. ## Change - New `core/_mps_sdpa_guard.py`. On Apple Silicon with MPS it wraps `torch.nn.functional.scaled_dot_product_attention`. An MPS call that has more than 2^28 score elements (the bound `diffusion_qwenimage21_math.MPS_SCORE_ELEMENTS` already uses) and that the prefill kernel would not take (`mps_prefill_attention`) runs in query-row chunks, which are then concatenated. - Every query row is independent, so the result is the same as one call. - Masks whose query axis is the full length are sliced with the rows. `is_causal` becomes the matching top-left-aligned bool mask for each chunk. - `scale`, `dropout_p` and `enable_gqa` are passed through. - Calls under the cap, calls the prefill kernel serves (torch 2.13+) and all non-MPS calls go to SDPA unchanged. - `UNSLOTH_MPS_ATTENTION_GUARD=0` turns it off. - `diffusion_attention._apply_attention_backend_impl` installs it for MPS image and video loads. The training worker does not need it: its Apple Silicon fallback without a usable MLX stack runs on CPU tensors, where the guard never splits. It is idempotent and a no-op off macOS. diffusers' native backend, its SDPA processors and transformers all look up the function on every call, so this covers every family. Qwen-Image-2.1 keeps its own bounded processor (segmented prefill, cached decode). Its calls are already under the cap, so they pass straight through. ## Tests - `tests/test_mps_attention_guard_on_load.py` (CPU): an MPS load wraps SDPA once, the wrapped function stays bit-identical off MPS, and CPU / CUDA loads keep the stock function. Fails on main, passes here. - `tests/test_mps_large_attention_guard.py` (CPU, with CPU tensors standing in for MPS and a small cap), 25 tests: - The split matches one fp64 call for bool and float masks of shapes `[B,H,Sq,Sk]`, `[B,1,Sq,Sk]`, `[1,1,1,Sk]`, `[B,1,1,Sk]`, `[Sq,Sk]` and `[1,Sk]`. - It also matches for `is_causal` with Sq = Sk, Sq > Sk and Sq < Sk, for GQA with a custom scale, for 3-D inputs, and through autograd. - Calls under the cap, prefill calls and off-MPS calls are untouched. - The install gating works. - Mutation check: dropping the mask slicing fails 6 tests, and dropping the causal mask fails 3. - `tests/test_mps_attention_families.py`: `test_the_guard_fixes_the_studio_measured_threshold` runs the same past-threshold cells as `test_past_the_studio_measured_threshold`, with the guard installed. It asserts that the guard split the call on torch < 2.13 and left it alone on 2.13+. - `test_differential.py`: DISCRIMINATING, head_fail=0. - `tests/test_diffusion_attention*.py`, `tests/test_rocm_windows_wide_head_sdpa.py` and the new files: 557 passed, 2 skipped on CPU. ### macOS 15 runner (GitHub Apple Silicon, main vs this branch, same job) Past-threshold cells (2^29.05 score elements, bf16, worst cosine against fp64 over 4 heads x 192 rows; growth is the MPS driver allocation during the call): | family | torch 2.11 main | torch 2.11 this PR | torch 2.13 main | torch 2.13 this PR | |---|---|---|---|---| | z-image | cos 0.000000, 2436 MiB | cos 0.999999, 204 MiB | cos 0.999992, 1024 MiB | cos 0.999992, 1024 MiB | | flux2-klein-4b | cos 0.000000, 2084 MiB | cos 0.999999, 1032 MiB | cos 0.999992, 1024 MiB | cos 0.999992, 1024 MiB | | qwen-image-2.1 | cos 0.000000, 2090 MiB | cos 0.999999, 1024 MiB | cos 0.999992, 1024 MiB | cos 0.999992, 1024 MiB | | sd3.5-large | cos 0.000000, 2078 MiB | cos 0.999999, 1032 MiB | cos 0.999995, 1024 MiB | cos 0.999995, 1024 MiB | - On torch 2.11, the guard split each of these calls once (`chunked_calls=1`). On torch 2.13 it split none (`chunked_calls=0`), because the prefill kernel takes them. - The head selection was 79 passed on both torch versions: the small-size cells for 8 families x 2 sizes x 3 dtypes, the key-padding mask cell, the 25 guard tests and the guarded large cells. - On main, torch 2.11 failed the 4 past-threshold cells, and torch 2.13 passed them. ## Not proven here - These are GitHub's virtual Apple Silicon runners. They prove correctness, not speed on real Macs. Chunking can add some per-call overhead on torch 2.11, and that was not timed. - No full image render on torch 2.11 was compared before and after. The proof is the attention call at each family's shape. - macOS 14 and torch versions between 2.11 and 2.13 (2.12) did not run.
… fused-MPS-attention release on re-run (#20038) ## Problem New Apple Silicon homes get torch 2.13 (#18428), because 2.13 is the first release with the fused MPS prefill attention kernel. Studio only enables that kernel on torch 2.13 or newer (`mps_prefill_supported` in `diffusion_attention.py`). An existing home keeps whatever torch it has, from 2.4 up to 2.14, unless the user sets `UNSLOTH_TORCH_UPGRADE=1`. So every Mac that was installed before #18428 keeps its old torch and runs diffusion on the math-only attention path. On a MacBook Pro M5 Max with the same Studio backend and the same prompts, warm time per 1024x1024 image was: | Pipeline | torch 2.10.0 (that Mac's existing home) | torch 2.14.1 | |---|---|---| | FLUX.2 klein, bf16 | 8.60 s | 3.69 s | | FLUX.2 klein, GGUF | 11.30 s | 6.39 s | | Z-Image, GGUF | 64.37 s | 18.00 s | Peak memory was also 3 to 5 GB lower on the newer torch. A large-linear check showed no corruption on either version. The images are not pixel-identical across versions, because the MPS random generator stream changed between those releases. Within a single version, repeated runs are bit-identical. ## Change The change is in `install.sh`, on the macOS arm64 route only. On a re-run, an existing home whose resident torch is a plain release below `_MACOS_TORCH_MOVE_FLOOR` (2.13.0, the release Studio's fused MPS attention gate needs) now takes the same `torch>=2.13.0,<2.14.0` / `torchvision>=0.28.0,<0.29.0` constraint that a new home gets. torchaudio resolves to 2.11.x, as it does on a new home. This happens only when every gate of the new-install route already holds: - the package is `unsloth`; - the index is the default cpu index (an index set with `UNSLOTH_TORCH_INDEX_URL` or `UNSLOTH_TORCH_INDEX_FAMILY` never moves); - macOS 14 or later, with a GIL-enabled Python 3.10 to 3.14; - the released `unsloth` on PyPI admits torch 2.13. An unreachable or capped PyPI keeps the resident release. These cases are unchanged: - A home already on 2.13 or 2.14 is kept. - A home whose torch cannot be read, or holds a nightly, takes the same path as before. - `UNSLOTH_TORCH_UPGRADE=0` (any value other than empty or `1`) keeps the resident release. - `UNSLOTH_TORCH_UPGRADE=1` behaves as before. The move floor is its own literal, not derived from `_MACOS_NEW_INSTALL_TORCH`. A later bump of the new-install pin (for example to 2.14) therefore never moves a 2.13 home. Homes below 2.13 move to whatever the pin is at that point. The installer prints `existing install has torch X -- moving to torch>=2.13.0,<2.14.0 for the fused MPS attention kernel (set UNSLOTH_TORCH_UPGRADE=0 to keep it)`. This follows the rule the installer already uses for a raised floor (#7250): a release below a route's floor is outside the preservation window, so it moves. On ROCm 7.2 and Strix, that floor is 2.11. Here it is 2.13. Linux, WSL, Windows (`install.ps1` is untouched), Intel macOS, CUDA, ROCm and XPU take exactly the same decisions as before. The new code runs only inside the macOS arm64 branch, and the shared pin block skips `_previous_torch_pin` only when that branch has decided to move. ### Why existing homes were preserved, and why this is safe on Apple Silicon - #6959 / #7250: a re-run should keep the torch release a user has validated. The trigger was a silent 2.10 to 2.11 move on a CUDA host. That still holds at or above 2.13 here. - #12150: on CUDA, the torch release is tied to prebuilt flash-attn, causal-conv1d and mamba-ssm wheels. `studio update` can also re-resolve torch under an older release's cap. Apple Silicon has no such prebuilt kernels. The PyPI gate is kept, and #18659 freezes the resident torch through `studio update` on Apple Silicon, so a moved home stays on 2.13 there. - torchcodec is chosen from the resident torch on every `install_python_stack.py` pass, so it follows the move. - A re-run rebuilds the venv anyway. A failed install rolls back to the previous environment, unless `--no-rollback` was passed. ## Tests - `tests/sh/test_macos_torch213_route.sh`: 132 checks. 22 fail on main. 3 more fail on a version of this branch that derived the floor from the pin: the floor literal, and a pin bumped to 2.14 still keeping 2.13.0 and 2.13.1 homes. - Existing 2.6 / 2.10 / 2.11 / 2.12.1 homes, and 2.10.0+cpu, move to the 2.13 constraint and announce the opt-out. - These homes are kept: 2.13.0 / 2.13.1 / 2.14.0 / 2.14.1; `UNSLOTH_TORCH_UPGRADE=0|false|no`; a pinned index; macOS 13; free-threaded Python; Python 3.9; another `--package`; an unreachable or capped PyPI. - With the pin bumped to 2.14 in the test: 2.13.0 and 2.13.1 homes are kept, and a 2.10 home moves to the bumped pin. - These are unchanged: a nightly, a release under the window floor, `--no-torch`, Intel macOS, and Linux / WSL / Windows on the cpu and cu128 indexes. - Unchanged and passing: `test_cu130_torch213_route.sh` (104), `test_previous_torch_pin.sh` (50), `test_get_torch_index_url.sh` (109), `test_torch_constraint.sh`, and `tests/python/test_macos_torch213_pins.py`. - Whole `tests/sh` suite: all 101 scripts pass on this branch, and all of them pass on the merge base too (the base runs its own copy of the route test). - Workflow lints: `scripts/lint_workflow_triggers.py` and actionlint pass. 58 test files read the workflow files: 3655 passed. The 2 failures (`test_cached_paths_hold_no_credentials`, `test_version_compat_bundle` daily sweep) fail the same way on the merge base, because of this host's environment. ## Upgrade run on macOS 15 `.github/workflows/studio-mac-torch-floor-upgrade.yml` (helper `.github/scripts/mac-torch-floor-upgrade.sh`) runs on macos-15 with Python 3.13 and 3.10. It starts a home with the merge base installer and moves it to torch 2.10.0 / torchvision 0.25.0 / torchaudio 2.10.0. Then it checks: - A: re-running the merge base installer keeps 2.10. - B: re-running this branch's installer moves the home to 2.13.x / 0.28.x / 2.11.x, with MPS available and MPS attention matching an fp64 CPU reference. - B2: a second re-run, then `unsloth studio update --local`, keep 2.13. - C: `UNSLOTH_TORCH_UPGRADE=0` keeps a 2.10 home. - D: a 2.14.1 home is kept. The workflow runs on dispatch, and on pull requests only outside `unslothai/unsloth`. On this repository's pull requests the job is skipped, so it takes no macOS runner. It also skips drafts. Results: pending. ## Not covered - The Desktop automatic startup repair runs the installer without `UNSLOTH_TORCH_UPGRADE`, so a repair of a home below 2.13 now moves it to 2.13 as well. This is intended. Set `UNSLOTH_TORCH_UPGRADE=0` in the environment to keep the resident torch. - The Desktop app updates through `unsloth studio update`, which never runs `install.sh`. A Desktop home that is never repaired or re-installed keeps its torch. It moves through Settings > Repair installation, which already sets `UNSLOTH_TORCH_UPGRADE=1`. Follow-up: a Studio "Repair recommended" hint for Apple Silicon homes below 2.13, like the Windows one in #19870. - GitHub's macOS runners are virtual machines, so they show that the install works, not how fast it runs.
Problem
install.shcaps torch below 2.12 on every route except cu130, so Apple Silicon installs get torch 2.11. On MPS, only torch 2.13 and later have a fused (prefill) SDPA kernel. Below that, every attention call materialises the full score matrix, which:Studio guards only Qwen-Image-2.1 against it.
The mflux pin (
mflux==0.22.0, installed with--no-deps) also declarestorch>=2.13.0, so today every Mac runs mflux below its declared floor.Change
New macOS arm64 installs take torch 2.13 / torchvision 0.28 / torchaudio 2.11.x from the default cpu index when all of these hold:
macosx_14_0);unslothon PyPI admits torch 2.13, as on the cu130 route.Existing homes keep their resident 2.4 to 2.14 torch unless
UNSLOTH_TORCH_UPGRADE=1. Linux, Windows, CUDA, ROCm, XPU, the CPU route and the generic ceiling are unchanged. torch 2.15 is not used, because it has no cp310 macOS wheel and no torchvision 0.30.Tests
tests/sh/test_macos_torch213_route.sh: 71 checks that replay the route decision. Fails on main, passes here.tests/python/test_macos_torch213_pins.py: 5 tests on the pinned trio and the torchcodec mapping.studio/backend/tests/test_mps_attention_families.py(skipped without MPS): MPS attention against a CPU fp64 reference at each image family's head shape, in fp32 / fp16 / bf16, plus a mask case. It records whether the prefill kernel engaged.test_get_torch_index_url109,test_previous_torch_pin50 and the rest), as do the Python install suites (170 + 119 + 127). shellcheck reports the same warnings as main.macOS 15 runner (GitHub Apple Silicon, main vs this branch)
Fresh-home
./install.sh --local:MPS attention against a CPU fp64 reference,
tests/test_mps_attention_families.py:So on torch 2.11 the attention output past that size is wrong, not only slower, for every family tested. Only Qwen-Image-2.1 has a guard today. Existing Mac homes stay on their torch unless
UNSLOTH_TORCH_UPGRADE=1, so a follow-up should widen the guard to every family on torch below 2.13.These are GitHub's virtual Apple Silicon runners: they prove installs and correctness, not speed on real Macs.